//接收数据库
let { studentsModel } = require('../models/studentsModel');
//暴露新增学生数据
module.exports.createStudents = async function(req, res) {
        const data = req.body;
        // console.log(data, 'fsfasfsegse');
        await studentsModel.create(data);
        const result = await studentsModel.find(data);
        if (result.length > 0) {
            res.send({
                message: '增加成功',
                code: 1
            })
        } else {
            res.send({
                message: '增加失败',
                code: 0
            })
        }

    }
    //暴露渲染学生数据
module.exports.getStudents = async function(req, res) {
    const { pageSize, currentPage, type = 'name', value = '' } = req.query;
    //获取学生总条数,或者满足搜索条件的总条数
    const total = await studentsModel.countDocuments({
        [type]: { $regex: value, $options: '$i' }
    });
    //计算总页数
    let pages = 1;
    if (pageSize) {
        pages = Math.ceil(total / pageSize);
    }
    const result = await studentsModel
        .find({
            [type]: { $regex: value, $options: '$i' }
        })
        .populate('classesId majorId')
        .limit(pageSize - 0)
        .skip((currentPage - 1) * pageSize);
    // console.log(result);
    res.send({
        message: '获取学生数据成功',
        code: 1,
        result: { total, pages, rows: result }
    })
}

//删除
module.exports.delStudents = async function(req, res) {
        const data = req.query;
        // console.log(data);
        await studentsModel.deleteOne(data);
        res.send({
            message: '删除成功',
            code: 1,
        })

    }
    //修改学生
module.exports.changeStudents = async function(req, res) {
    const data = req.query;
    const result = await studentsModel.find(data).populate('classesId majorId');
    if (result.length > 0) {
        res.send({
            message: '修改成功',
            code: 1,
            result
        })

    } else {
        res.send({
            message: '修改失败',
            code: 0
        })
    }

}
module.exports.subChangeStudents = async function(req, res) {
    const { _id, name, age, gender, classesId, majorId } = req.body;
    console.log({ _id });
    await studentsModel.updateOne({ _id }, { name });
    await studentsModel.updateOne({ _id }, { age });
    await studentsModel.updateOne({ _id }, { gender });
    await studentsModel.updateOne({ _id }, { classesId });
    await studentsModel.updateOne({ _id }, { majorId });
    res.send({
        message: '修改成功',
        code: 1


    })
}